package top.infopub.job.quartz.exec.base;


import java.util.Date;

import org.quartz.Job;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import top.infopub.job.util.BizMailWarn;
import top.infopub.model.job.ScheduleLog;
import top.infopub.tdp.job.service.ScheduleLogService;
import top.infopub.util.SpringContext;


/**
 * 主要实现日志记录，所有job必须extends BaseJob
 * @author Awoke
 * @version 2018年9月27日
 * @see BaseJob
 * @since
 */
public abstract class BaseJob implements Job {

    protected final Logger log = LoggerFactory.getLogger(this.getClass());

    private static ScheduleLogService logService;

    static {
        logService = SpringContext.getBean(ScheduleLogService.class);
    }

    /**
     * 执行成功日志
     * @see
     */
    protected void logSucceed() {
        final ScheduleLog log = new ScheduleLog();
        log.setTexecuteTime(new Date());
        log.setIresult("1");
        log.setSremark("执行成功");
        log.setStaskName(this.getClass().getSimpleName());
        logService.insert(log);
    }

    /**
     * 执行成功日志
     * @see
     */
    protected void logSucceed(String memo) {
        final ScheduleLog log = new ScheduleLog();
        log.setTexecuteTime(new Date());
        log.setIresult("1");
        log.setSremark("执行成功" + "；" + memo);
        log.setStaskName(this.getClass().getSimpleName());
        logService.insert(log);
    }

    /**
     * 执行异常日志
     * @param ex 执行成功日志 异常
     * @param isWarning 执行异常时，是否告警，true为告警
     * @see
     */
    protected void logFail(Exception ex, boolean isWarning) {
        log.error("job error", ex);
        final ScheduleLog log = new ScheduleLog();
        log.setTexecuteTime(new Date());
        log.setIresult("0");
        log.setSremark("执行异常，" + ex.getClass().getName() + " error-msg : " + ex.getMessage());
        log.setStaskName(this.getClass().getSimpleName());
        logService.insert(log);
        if (isWarning) {
            StringBuilder msg = new StringBuilder("调度任务：");
            msg.append(log.getStaskName());
            msg.append("，执行失败，备注信息：");
            msg.append(log.getSremark());
            BizMailWarn.send("[znjt]调度中心任务执行异常告警", msg.toString());
        }

    }

}
